﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;

using XNADota;

namespace XNADota.AnimationModelXFile
{
    class AnimationModel
    {
        private XNADota game;
        private AnimationPlayer player;
        private Dictionary<string, AnimationClip> animationClips;
        private Model model;
        List<ModelMeshPart> meshParts = new List<ModelMeshPart>();
        AnimationModelEffect animationModelEffect;

        public AnimationPlayer Player
        {
            get { return player; }
        }

        public AnimationModel(XNADota game)
        {
            this.game = game;
        }

        public void LoadModel(string folderName, string fileName)
        {
            this.model = this.game.Content.Load<Model>(folderName + "\\" + fileName);

            if (model.Tag == null)
            {
                throw new ArgumentException("Animation Model.Tag should not be null");
            }
            else
            {
                Dictionary<string, Object> dictionary = model.Tag as Dictionary<string, object>;
                this.player = new AnimationPlayer(dictionary["SkinningData"] as SkinningData);
                this.animationClips = dictionary["AnimationData"] as Dictionary<string, AnimationClip>;
            }

            this.animationModelEffect = new AnimationModelEffect(model.Meshes[0].Effects[0]);
        }

        // here only set one player
        public void ChangeAnimation(int k)
        {
            foreach (AnimationClip animationClip in animationClips.Values)
            {
                this.player.StartClip(animationClip, true);
                if (k-- <= 0) break;
            }
        }

        public void Update(GameTime gameTime)
        {
            TimeSpan time = new TimeSpan((long)(gameTime.ElapsedGameTime.Ticks));
            this.player.Update(time, true, Matrix.Identity);
        }

        public void SetEffects()
        {
            animationModelEffect.Bones = player.GetSkinTransforms();
            
            animationModelEffect.World = Matrix.Identity;
            animationModelEffect.View = this.game.CameraManager.ActiveCamera.View;
            animationModelEffect.Projection = this.game.CameraManager.ActiveCamera.Projection;

            animationModelEffect.NumLight = 1;
            animationModelEffect.VecEye = new Vector4(this.game.CameraManager.ActiveCamera.Position, 0);
        }

        public void Draw()
        {
            SetEffects();

            foreach (ModelMesh mesh in this.model.Meshes)
            {
                mesh.Draw();
            }

        }
    }
}
